using System;
using System.IO;
using System.Data;
using System.Net;
using MyClever.Lib;

namespace MyClever.DefaultPlugins
{
    public class FTPDownload : MissionPlugin
    {
        [Package(Direction.Input, "Defines the access settings for a ftp server.")]
        enum FTP_Settings
        {
            [Column(typeof(string), "The directory, where you like to download files.")]
            DirectoryURLPath,
            [Column(typeof(string), "The user name associated with the ftp server.")]
            UserName,
            [Column(typeof(string), "The password for the user name associated with the ftp server.")]
            Password
        }

        [Package(Direction.Input, "Defines all files you like to download from your ftp server.")]
        enum DownloadFiles
        {
            [Column(typeof(string), "The file you like to download to your desktop machine.")]
            FileName
        }

        [Package(Direction.Input, "Defines all the download settings.")]
        enum DownloadFolders
        {
            [Column(typeof(string), "The directory, where you like to download your files.",
               Validation = "ispath")]
            DownloadPath
        }

        [Plugin(PluginDevStatus.Production, "Downloads the given files to the expected directories.", 
            Author="Mathias Mielitz", Email="m.mielitz@mycleverfriend.org", Tags="ftp download")]
        public FTPDownload()
        {
        }

        public override void Initialize()
        {
            //This is the first Function called by the host...
            //Put anything needed to start with here first
        }

        public override void Dispose()
        {
            //Put any cleanup code in here for when the program is stopped
        }

        protected override void Work()
        {
            DataTableReader downloadSettings = this.GetDataReader(typeof(DownloadFolders));
            while (downloadSettings.Read())
            {
                this.AddNewLoggingMessage(typeof(DownloadFolders), String.Format("create folder if not exist: '{0}'", downloadSettings[DownloadFolders.DownloadPath.ToString()].ToString()));

                // Create the subfolder if not existing
                if (false == Directory.Exists(downloadSettings[DownloadFolders.DownloadPath.ToString()].ToString()))
                {
                    System.IO.Directory.CreateDirectory(downloadSettings[DownloadFolders.DownloadPath.ToString()].ToString());
                }

                // get the ftp settings
                DataTableReader ftpSettings = this.GetDataReader(typeof(FTP_Settings));
                while (ftpSettings.Read())
                {
                    // get all download files
                    DataTableReader downloadFiles = this.GetDataReader(typeof(DownloadFiles));
                    while (downloadFiles.Read())
                    {
                        string ftpFullPath = ftpSettings[FTP_Settings.DirectoryURLPath.ToString()].ToString() + "/" + downloadFiles[DownloadFiles.FileName.ToString()].ToString();

                        this.AddNewLoggingMessage(typeof(DownloadFiles), String.Format("download file: '{0}'", ftpFullPath));

                        FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpFullPath);
                        ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
                        ftpRequest.Credentials = new NetworkCredential(ftpSettings[FTP_Settings.UserName.ToString()].ToString(), ftpSettings[FTP_Settings.Password.ToString()].ToString());
                        ftpRequest.UsePassive = true;
                        ftpRequest.UseBinary = true;
                        ftpRequest.KeepAlive = false;

                        FileStream outputStream = new FileStream(downloadSettings[DownloadFolders.DownloadPath.ToString()].ToString() + "\\" + downloadFiles[DownloadFiles.FileName.ToString()].ToString(), FileMode.Create);

                        FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
                        Stream ftpStream = response.GetResponseStream();
                        long cl = response.ContentLength;
                        int bufferSize = 3145728;
                        int readCount;
                        byte[] buffer = new byte[bufferSize];

                        readCount = ftpStream.Read(buffer, 0, bufferSize);
                        while (readCount > 0)
                        {
                            outputStream.Write(buffer, 0, readCount);
                            readCount = ftpStream.Read(buffer, 0, bufferSize);
                        }

                        ftpStream.Close();
                        outputStream.Close();
                        response.Close();
                        ftpRequest.Abort();
                    }
                }
            }
        }  
    }
}
